package com.jwgf.fault;

import java.io.InputStream;
import java.util.HashMap;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.jwgf.common.AppContext;

public class PullFaultParse implements IXmlParse {

	@Override
	public HashMap<Integer, FaultContent> getFaultMapByParseXml(InputStream is) throws Exception {
		HashMap<Integer, FaultContent> faultMap = null;
		int key = 0;
		String value = null;
		int drawable_id = 0;
		String detail = null;

		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		XmlPullParser parser = factory.newPullParser();
		parser.setInput(is, "utf-8");
		int type = parser.getEventType();

		while (type != XmlPullParser.END_DOCUMENT) {
			String tagName = parser.getName();
			switch (type) {
			case XmlPullParser.START_DOCUMENT:
				faultMap = new HashMap<Integer, FaultContent>();
				break;
			case XmlPullParser.START_TAG:
				if ("Fault".equals(tagName)) {
					key = 0;
					value = null;
					drawable_id = 0;
					detail = null;
				} else if ("code".equals(tagName)) {
					key = Integer.parseInt(parser.nextText(), 16);
				} else if ("value".equals(tagName)) {
					value = parser.nextText();
				} else if ("drawable".equals(tagName)) {
					drawable_id = AppContext
							.getInstance()
							.getResources()
							.getIdentifier(parser.nextText(), "drawable",
									AppContext.getInstance().getPackageName());
				} else if ("detail".equals(tagName)) {
					detail = parser.nextText();
				}
				break;
			case XmlPullParser.END_TAG:
				if ("Fault".equals(tagName)) {
					faultMap.put(key, new FaultContent(value, detail,
							drawable_id));
				}
				break;
			}

			type = parser.next();
		}
		return faultMap;
	}

}
